package com.demon.net

import com.demon.logger.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.coroutineScope

/**
 * <p>
 * [类说明]
 * </p>
 *
 * @author zhaozeyang
 * @since 2020/5/18
 */
class AppResponseExecutor : IExecutor {
    override suspend fun <T : Any> executeRequest(
        call: suspend () -> IAppResponse<T>,
        successBlock: (suspend CoroutineScope.() -> Unit)?,
        errorBlock: (suspend CoroutineScope.() -> Unit)?
    ): ResponseResult<T> {
        val response: IAppResponse<T>?
        try {
            response = call.invoke()
        } catch (e: Exception) {
            Logger.e("Request", "网络请求出错", e)
            return ResponseResult.HttpError(e)
        }
        return coroutineScope {
            when {
                // 调用成功返回结果
                response.isSuccess() -> {
                    successBlock?.let { it() }
                    ResponseResult.Success(response.getResponseData())
                }
                // Session过期
                response.isExpired() -> {
                    ResponseResult.Expired(response.getResponseMessage())
                }
                // 调用失败
                response.isFailed() -> {
                    ResponseResult.Failed(
                        ApiError(
                            response.getResponseMessage(),
                            response.getResponseCode()
                        )
                    )
                }
                else -> {
                    errorBlock?.let { it() }
                    ResponseResult.Failed(
                        ApiError(
                            response.getResponseMessage(),
                            response.getResponseCode()
                        )
                    )
                }
            }
        }
    }
}